package com.example.educationai.controller;

import com.example.educationai.entity.Exam;
import com.example.educationai.entity.ExamRecord;
import com.example.educationai.service.ExamService;
import com.example.educationai.service.ExamRecordService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/exam-submit")
public class ExamSubmitController {

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamRecordService examRecordService;

    @GetMapping
    public String showSubmitForm(@RequestParam(required = false) Long examId, 
                               Model model,
                               RedirectAttributes redirectAttributes) {
        if (examId == null) {
            redirectAttributes.addFlashAttribute("error", "请选择要提交的考试");
            return "redirect:/exam/list";
        }
        
        Exam exam = examService.getExam(examId);
        model.addAttribute("exam", exam);
        model.addAttribute("record", new ExamRecord());
        return "exam/submit";
    }

    @PostMapping
    public String submitExam(@ModelAttribute ExamRecord record,
                           @RequestParam("examImage") MultipartFile examImage,
                           @RequestParam Long examId,
                           HttpSession session,
                           RedirectAttributes redirectAttributes) {
        try {
            Exam exam = examService.getExam(examId);
            record.setExam(exam);
            record.setStudentName((String) session.getAttribute("studentName"));
            
            examRecordService.createRecord(record, examImage);
            
            redirectAttributes.addFlashAttribute("success", "试卷提交成功");
            return "redirect:/exam/list";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "提交失败：" + e.getMessage());
            return "redirect:/exam-submit?examId=" + examId;
        }
    }
} 